package com.itheima.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.BdMapper;
import com.itheima.pojo.Article;
import com.itheima.service.BdService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class bdServiceImpl extends ServiceImpl<BdMapper, Article> implements BdService {

    @Autowired
    private BdMapper bdMapper;

    /**
     * 调用 mapper 查询
     *
     * @return
     */
    @Override
    public List<Article> findAll() {
        List<Article> top = bdMapper.findAll();
        //判断
        if (top.size() == 0) {
            throw new RuntimeException("没有排行榜...");
        }
        return top;
    }

    /**
     * 点赞,收藏,评论 加分
     * @param id
     * @param status
     * @return
     */
    @Override
    public Map addById(Long id, Integer status) {
        Map map = new HashMap();
        //1.检查参数:当id=0或者操作的不是1,2,3则是错误的,参数就是异常
        if (id == 0 || (status != 1 && status != 2 && status != 3)) {
            map.put("ststus", false);
            map.put("message", "参数异常");
            return map;
        }
        //2.根据文章查到对象
        Article article = bdMapper.selectById(id);

        //判断得到的对象不等于null
        if (article == null) {
            map.put("ststus", false);
            map.put("message", "文章不存在");
            return map;
        }
        //当文章存在,选择需要执行的操作时,对应加分
        if (status == 1) {//点赞的
            article.setLikes(article.getLikes() + 1);
        } else if (status == 2) {//收藏的
            article.setCollection(article.getCollection() + 1);
        } else if (status == 3) {//评论的
            article.setComment(article.getComment() + 1);
        }

        //更新数据库的数据
        bdMapper.updateById(article);

        map.put("ststus", true);
        map.put("message", "添加成功!!");
        return map;
    }
}
